﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Media;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace 桌面视频录制
{
    class StaticFunction
    {
        public static int R = 7;
        public static Brush Brush = Brushes.Red;
        public static Random random = new Random();//一个该项目的随机数生成对象
        public static SoundPlayer soundPlayer = new SoundPlayer();
        /// <summary>
        /// 获取一个本机可用的端口号
        /// </summary>
        public static int GetAvailablePort()
        {
            int port;
            TcpListener testListener;
            while (true)
            {
                port = StaticFunction.random.Next(10000, 51000);
                try
                {
                    testListener = new TcpListener(StaticFunction.GetHostIP(), port);
                    testListener.ExclusiveAddressUse = true;
                    testListener.Start();
                }
                catch
                {
                    continue;
                }
                testListener.Stop();
                return port;
            }
        }
        /// <summary>
        /// 获取本机的IPV4地址
        /// </summary>
        public static IPAddress GetHostIP()
        {
            //return IPAddress.Parse("5.130.54.71");
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in ips)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    return ip;
            }
            return ips[0];
        }
       
        [DllImport("user32.dll")]
        //让窗口闪烁
        public static extern bool FlashWindow(IntPtr hwnd, bool bInvert);
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        public static byte[] Serialize(DrawObject drawObject)
        {
            IFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, drawObject);
                return ms.GetBuffer();
            }
        }
        public static DrawObject Deserialize(byte[] bs)
        {
            using (MemoryStream ms = new MemoryStream(bs))
            { 
                IFormatter formatter = new BinaryFormatter();
                DrawObject drawObject = formatter.Deserialize(ms) as DrawObject;
                return drawObject;
            }
        }
        public static Rectangle GetControlRect(Point point)
        {
            return new Rectangle(point.X - 3, point.Y - 3, StaticFunction.R, StaticFunction.R);
        }
        public static void DrawControlRegion(Graphics g, Point point)
        {
            g.FillEllipse(StaticFunction.Brush, GetControlRect(point));
        }
    }
}
